import 'package:ad_common/third_ad.dart';
import 'package:ad_common/third_ad_instance.dart';
import 'package:ad_plugin/ad_listener.dart';
import 'package:flutter/foundation.dart';

import 'ad_container.dart';
import 'ad_error.dart';
import 'ad_manager.dart';
import 'ad_source.dart';

/// FileName insert_ad
/// @Author zhuqingfang
/// @Date 2022/10/8 11:00 上午
/// @Description insert ad
class InsertAd extends Ad{
  final AdLoadCallback<InsertAd> adLoadCallback;
  ContentCallback<InsertAd>? contentCallback;
  InsertAd._(
      {required String placementId,
        required this.adLoadCallback})
      : super(placementId: placementId);
  static load(
      {required String placementId,
        required AdLoadCallback<InsertAd> adLoadCallback}) {
    InsertAd insertAd = InsertAd._(
        placementId: placementId, adLoadCallback: adLoadCallback);
    SourceAdType source;
    switch(AdGlobalParamsManager.instance.getAdSource()){

      case AdSource.topOn:
        source = SourceAdType.topOnInsertAd;
        break;
      case AdSource.google:
        source = SourceAdType.adMobInsertAd;
        break;
      default:
        source = SourceAdType.topOnInsertAd;
        break;
    }
    insertAd.loadConfig(source);
    insertAd.thirdAdParams = ThirdAdParams(
        appId: AdGlobalParamsManager.instance.getAdAppId(),
        appKey: AdGlobalParamsManager.instance.getAdAppKey(),
        placementId: placementId,
        thirdAdEventCallback:
            (AdCallbackEvent adCallbackEvent, String message,Object extraInfo) {
          debugPrint("ad callback $adCallbackEvent message:$message");
          switch(adCallbackEvent) {
            case AdCallbackEvent.adLoaded:
              insertAd.adLoadCallback.onAdLoaded(insertAd);
              break;
            case AdCallbackEvent.adLoadFail:
              LoadAdError loadAdError = LoadAdError(-1, message);
              insertAd.adLoadCallback.onAdFailLoad(insertAd,loadAdError);
              break;
            case AdCallbackEvent.adOnShow:
              insertAd.contentCallback?.onAdShow(insertAd);
              break;
            case AdCallbackEvent.adOnDismissed:
              insertAd.contentCallback?.onAdDismiss(insertAd);
              break;
            case AdCallbackEvent.adOnClicked:
              insertAd.contentCallback?.onAdClick(insertAd);
              break;
            default:
              LoadAdError loadAdError = LoadAdError(-1,message);
              insertAd.adLoadCallback.onAdFailLoad(insertAd,loadAdError);
              break;
          }
        });
    if (thirdAdInstance.adSourceMap.containsKey(insertAd.sourceType)) {
      insertAd.thirdAd = thirdAdInstance
          .adSourceMap[insertAd.sourceType](insertAd.thirdAdParams);
      insertAd.thirdAd.load();
    }
  }
}